#coding:utf-8
import os
import chardet
from ConfigParser import RawConfigParser as rcp
import dict4ini

def cdWalker(cdrom, cdcfile):
    '''光盘扫描主函式
    @param cdrom: 光盘访问路径
    @param cdcfile: 输出的光盘信息记录文件（包含路径，绝对，相对都可以）
    @return: 无，直接输成转*.cdc文件
    @attention: 从v0.7开始不使用此扫描函式，使用inicdinfo()
    '''
    export = ''
    for root, dirs, files in os.walk(cdrom):
        export += formatCDinfo(root, dirs, files)
        #export += "\n %s;%s;%s" % (root, dirs, files)
    open(cdcfile, 'w').write(export)

def iniCDinfo(cdrom, cdcfile):
    '''光盘信息.ini格式化函式
    @note:直接利用 os.walk() 函式的输出信息由 ConfigParser.RawConfigParser进行重组处理.ini 格式文本输出并记录
    @param cdrom: 光盘访问路径
    @param cdcfile: 输出的光盘信息记录文件（包含路径，绝对相对路径都可以）
    @return: 无，直接输出成组织好的类.ini的*.cdc文件
    '''
    walker = {}
    for root, dirs, files in os.walk(cdrom):
        walker[root] = (dirs, files)            # 以root为key,以dir,files为值,并将值赋给root
        if '.svn' in dirs:
            dirs.remove('.svn')
    cfg = rcp()
    cfg.add_section("Info")
    cfg.add_section("Comment")
    cfg.set("Info", 'ImagePath', cdrom)
    cfg.set("Info", 'Volume', cdcfile)
    dirs = walker.keys()
    i = 0
    for d in dirs:
        i += 1
        cfg.set("Comment", str(i), d)
    for p in walker:
        cfg.add_section(p)
        for f in walker[p][1]:
            cfg.set(p, f, os.stat("%s/%s" % (p, f)).st_size)
    cfg.write(open(cdcfile, "w"))

'''代码问题，暂时还解决不了
def dictCDinfo(cdrom, cdcfile):
    walker = {}
    inifile = dict4ini.DictIni(cdcfile)
    inifile['Info']
    inifile.Info.ImagePath = cdrom
    inifile.Info.Volume = cdcfile
    inifile['Comment']
    #inifile.save()
    for root, dirs, files in os.walk(cdrom):
        walker[root] = (dirs, files)
        if '.svn' in dirs:
            dirs.remove('.svn')
        dirs = walker.keys()
        i = 0
        for d in dirs:
            i += 1
            inifile.Comment.i = d
        for p in walker:
            for f in walker[p][1]:
                inifile.p.f = os.stat("%s/%s"%(p, f)).st_size
        inifile.save()

'''
def cdcGrep(cdcpath, keyword):
    filelist = os.listdir(cdcpath)
    for cdc in filelist:
        if '.cdc' in cdc:
            cdcfile = open(cdcpath+cdc)
            print "关键词所在文件：%s%s" % (cdcpath, cdc)
            for line in cdcfile.readlines():
                if keyword in line:
                    print line

def _smartcode(stream):
    '''smart recove stream into UTF-8
    '''
    ustring = stream
    codedetect = chardet.detect(ustring)['encoding']
    print codedetect
    try:
        print ustring
        ustring = unicode(ustring, codedetect)
        print ustring
        return "%s %s" % ("", ustring.encode('utf8'))
    except:
        return u"bad unicode encode try!"
                    
def formatCDinfo(root, dirs, files):
    export = "\n"+root+"\n"
    for d in dirs:
        export += "-d "+root+_smartcode(d)+"\n"
    for f in files:
        export += "-f %s %s \n"%(root, _smartcode(f))

    export += "="*70
    return export

if __name__ == '__main__':
    cdrom = '/home/wwq/py/gp'
    cdWalker(cdrom, 'cdc/cdctools.cdc')
